package cn.skylark.wcm.common.util;

import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.*;

/**
 * UploadHelper
 *
 * @author chuhl
 * @date 2017/12/19
 */
public class UploadHelper {
    /**
     * @param request
     * @param allowExtName 不允许上传的文件扩展名
     * @return MultipartFile集合
     * @descrption 根据HttpServletRequest对象获取MultipartFile集合
     * @author chuhl
     */
    public static List<MultipartFile> getFileSet(MultipartHttpServletRequest request, String[] allowExtName) {
        long maxLength = 1024 * 2000000;
        Iterator<String> itr = request.getFileNames();
        MultiValueMap<String, MultipartFile> linkedHashMap = request.getMultiFileMap();
        //返回值
        List<MultipartFile> files = new LinkedList<MultipartFile>();
        while (itr.hasNext()) {
            String uploadedFile = itr.next();
            LinkedList<MultipartFile> linkedList = (LinkedList<MultipartFile>) linkedHashMap.get(uploadedFile);
            for (MultipartFile multipartFile : linkedList) {
                if (validateFile(multipartFile, maxLength, allowExtName)) {
                    files.add(multipartFile);
                }
            }
        }
        return files;
    }

    /**
     * @param file MultipartFile对象
     * @param path 保存路径，如“D:\\File\\”
     * @return 保存的全路径 如“D:\\File\\2345678.txt”
     * @throws Exception 文件保存失败
     * @descrption 保存文件
     * @author chuhl
     */
    public static String uploadFile(MultipartFile file, String path)
            throws Exception {

        String filename = file.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf("."))
                .toLowerCase();
        String lastFileName = UUID.randomUUID().toString() + extName;
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }
        File temp = new File(path);
        if (!temp.isDirectory()) {
            temp.mkdir();
        }
        // 图片存储的全路径
        String fileFullPath = path + lastFileName;
        FileCopyUtils.copy(file.getBytes(), new File(fileFullPath));
        return fileFullPath;
    }

    /**
     * @param file         MultipartFile对象
     * @param maxLength    文件最大限制
     * @param allowExtName 不允许上传的文件扩展名
     * @return 文件格式是否合法
     * @descrption 验证文件格式，这里主要验证后缀名
     * @author chuhl
     */
    private static boolean validateFile(MultipartFile file, long maxLength,
                                        String[] allowExtName) {
        if (file.getSize() < 0 || file.getSize() > maxLength) {
            return false;
        }
        String filename = file.getOriginalFilename();

        // 处理不选择文件点击上传时，也会有MultipartFile对象，在此进行过滤
        if (filename == "") {
            return false;
        }
        String extName = filename.substring(filename.lastIndexOf("."))
                .toLowerCase();
        if (allowExtName == null || allowExtName.length == 0
                || Arrays.asList(allowExtName).contains(extName)) {

            return true;
        } else {
            return false;
        }
    }

}
